/*
 * Copyright 2010 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.valdemar.android.givemeanswers;

import com.valdemar.android.givemeanswers.common.AnswersApplicationContext;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

/**
 * Main activity - requests "Hello, World" messages from the server and provides
 * a menu item to invoke the accounts activity.
 */
public class SplashScreenActivity extends BaseActivity
{
	/**
	 * Tag for logging.
	 */
	private static final String TAG = "GiveMeAnswersActivity";

	/**
	 * The current context.
	 */
	private Context mContext = this;

	protected int _splashTime = 2000;
	Thread splashTread;
	private static final int ACCOUNT_ACTIVITY_RESULT = 1;

	/**
	 * Begins the activity.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		Log.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);

		setContentView(R.layout.splash_screen);
		
		AnswersApplicationContext appContext = (AnswersApplicationContext) getApplicationContext();
		appContext.registerC2DMReceiver();
		

		SharedPreferences prefs = Util.getSharedPreferences(mContext);
		String connectionStatus = prefs.getString(Util.CONNECTION_STATUS, Util.DISCONNECTED);
		if (Util.DISCONNECTED.equals(connectionStatus))
		{
			startActivityForResult(new Intent(this, AccountsActivity.class), ACCOUNT_ACTIVITY_RESULT);
		}
		else
		{
			doWait();
		}
	}

	private void doWait()
	{
		splashTread = new Thread()
		{
			@Override
			public void run()
			{
				try
				{
					int waited = 0;
					while (waited < _splashTime)
					{
						sleep(100);
						waited += 100;
					}
				}
				catch (InterruptedException e)
				{
					return;
				}

				startActivity(new Intent(getBaseContext(), GiveMeAnswersActivity.class));
				finish();
			}
		};
		splashTread.start();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case ACCOUNT_ACTIVITY_RESULT:
				doWait();
				break;

			default:
				break;
		}

	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();

		if (splashTread != null)
		{
			splashTread.interrupt();
		}
	}

}
